from dj030201.settings import *
import pymysql
from datetime import datetime

class UserSignin:
    def __init__(self):
        self.logins = [] # 读取数据库中所有的账号
        self.loginId = ''
        self.loginPwd = ''
        self.error_info = ''    #加载错误信息
        self.signin_result = '' # 记录验证方法
        self.error_time = 0
        self.error_list = []
        self.current_name = ''

        self.error_pwd()

    def load_logins(self):
        '''
        读取数据库中所有的用户名和密码，春处在Logins集合里
        :return:
        '''
        mysql_db = pymysql.connect(host=DB_HOST, user=DB_USER, password=DB_PASSWORD, db=DB_NAME)
        cursor = mysql_db.cursor()
        sql = 'Select LoginId,LoginPwd,UserName,IsEnable,PositionName from login INNER JOIN Position on login.PositionId = position.PositionID'
        try:
            cursor.execute(sql)
            self.logins = cursor.fetchall()
        except Exception as e:
            self.error_info = '数据库出现异常，具体原因是：' + str(e)
        finally:
            mysql_db.close()

    def error_pwd(self):
        '''
        重置所有账号登录错误的次数
        :return:
        '''
        self.load_logins()
        results = self.logins
        for index in range(len(results)):
            self.error_list.append(0)

    def signin(self):
        '''
        登录调用的方法
        :return:
        '''
        # 每次验证完都更新数据
        self.load_logins()
        results = self.logins
        for index in range(len(results)):
            if results[index][0] == self.loginId:
                if results[index][3] == 0:
                    self.error_info = '用户已被禁用'
                    self.signin_result = 0
                    break
                if results[index][1] != self.loginPwd:
                    self.error_info = '密码错误'
                    self.error_list[index] += 1
                    self.signin_result = 0
                    if self.error_list[index] == 3:
                        self.disable_login()
                        self.error_info = '连续输错三次密码，用户已被禁用！'
                    break
                elif results[index][1] == self.loginPwd:
                    # 登录成功后重置错误次数
                    self.error_pwd()
                    print('重置成功')
                    # 更新最近登录时间
                    self.update_last_login_time()
                    # 获得登录的名字
                    self.current_name = results[index][2]
                    print('记录登录时间成功')
                    if results[index][4] == '收银员':
                        self.signin_result = 1
                        break
                    elif results[index][4] == '管理员':
                        self.signin_result = 2
                        break
            if index == len(results)-1:
                self.error_info = '没有该用户'
                self.signin_result = 0
                break
        pass

    def disable_login(self):
        '''
        禁用账户的方法
        :return:
        '''
        mysql_db = pymysql.connect(host=DB_HOST, user=DB_USER, password=DB_PASSWORD, db=DB_NAME)
        cursor = mysql_db.cursor()
        sql = 'update Login set IsEnable = 0 where LoginId = {}'.format(self.loginId)
        try:
            cursor.execute(sql)
            # 提交
            mysql_db.commit()
        except Exception as e:
            # 撤销
            mysql_db.rollback()
            self.error_info = '数据库出现异常，具体原因是：' + str(e)
        finally:
            mysql_db.close()
        pass

    def update_last_login_time(self):
        dt01 = datetime.now()
        print(dt01)
        mysql_db = pymysql.connect(host=DB_HOST, user=DB_USER, password=DB_PASSWORD, db=DB_NAME)
        cursor = mysql_db.cursor()
        sql = 'update Login set LastLoginTime = "{}" where LoginId = {}'.format(dt01,self.loginId)
        try:
            cursor.execute(sql)
            # 提交
            mysql_db.commit()
        except Exception as e:
            # 撤销
            mysql_db.rollback()
            self.error_info = '数据库出现异常，具体原因是：' + str(e)
        finally:
            mysql_db.close()
        pass



